/*
 * 微信登录方法
 */
import
jwt
from '@/utils/cache/jwt.js';
import {
	http
} from '@/utils/request/service.js';
/**
 * token过期后用户登录
 */
export const silentLogin = () => {
	return new Promise((resolve, reject) => {
		//1.存在openId则直接登录
		let openId = jwt.getOpenId();
		if (openId) {
			loginByOpenIdApi(openId)
				.then(({
					userInfo,
					token
				}) => {
					//登录成功
					jwt.setUser(userInfo)
					jwt.setAccessToken(token)
					resolve(userInfo)
				}).catch(() => {
					//当前页面加入缓存
					if (setCurrentPage()) {
						//登录失败,重新获取code/openId
						//提示用户登录信息已过期,即将重新登录
						getOAuth2CodeUrlApi()
					}
				})
		}else{
			//当前页面加入缓存
			if (setCurrentPage()) {
				//重新登录
				getOAuth2CodeUrlApi()
			}
		}
	})
}
/**
 * 通过openId登录
 */
export const loginByOpenIdApi = (openId) => {
	return http.post('/patient/anon/loginByOpenId', {
		openId
	})
}

/**
 * 通过code获取OpenId
 */
export const codeToOpenidApi = (code) => {
	console.log(code);
	return http.post('/anon/txmp/auth/codeToOpenid', {
		code
	})
}


//登录
/**获取codeUrl*/
export const getOAuth2CodeUrlApi = async () => {
	
	let redirectUrl = 'http://xlznwx.ftnet225.cn/xlznmp/'
	let {
		oAuth2CodeUrl
	} = await http.post('/anon/txmp/auth/snsApiBase', {
		redirectUrl
	})
	window.location.href = oAuth2CodeUrl
}

const currentPageKey = 'CURRENT_PAGE'

//设置CurrentPage
export const setCurrentPage = () => {
	try {
		let pathObj = getCurrentPagePath()
		console.log(pathObj);
		uni.setStorageSync(currentPageKey, pathObj);
		return true;
	} catch (e) {
		return false;
	}
}
//获取CurrentPage后立即清除
export const getAndRemoveCurrentPage = function() {
	try {
		let pathObj = uni.getStorageSync(currentPageKey)
		uni.removeStorageSync(currentPageKey)
		return pathObj
	} catch (e) {
		return false;
	}
}

export const getCurrentPagePath = ()=>{
	let pages = getCurrentPages()
	let len = pages.length
	let curParam = pages[len - 1].options //获取当前页面参数
	return {url:'/' + pages[len - 1].route,params:curParam}
}
